//
//  NearbyPathViewController.m
//  安好
//
//  Created by lianchuang on 14/12/3.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "NearbyPathViewController.h"
#import "BusListViewController.h"
#import "BaseNavigation.h"
#import "PersonViewController.h"
@interface NearbyPathViewController ()<BusListDelegate>

@end

@implementation NearbyPathViewController
{
    UILabel *detailLabel;
    NSInteger detailcount;
    MAPolyline *redline;
    NSMutableArray *zoomUpLats;
    NSMutableArray *zoomUpLngs;
    CGFloat height;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.mapView.delegate=self;
    self.locationManager.delegate=self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (kScreenWidth==414) {
        height=9;
    }
    else{
        height=0;
    }

    self.illHospitalLatArr=[[NSMutableArray alloc] init];
    self.illHospitalLonArr=[[NSMutableArray alloc]init];
    self.detailStepArray=[[NSMutableArray alloc]init];
    zoomUpLats=[[NSMutableArray alloc]init];
    zoomUpLngs=[[NSMutableArray alloc]init];
    detailcount=1;
    [self setnarBar];
    [self creatMapView];
    [self initToolbarwithDetail];
    
    NSArray *arrays=@[@"nearbyDrug_diringSelect.png",@"nearbyDrug_bus.png",@"nearbyDrug_walk.png"];
    NSArray *titleArray=@[@"开车",@"公交",@"步行"];
    for (int i=0; i<3; i++) {
        UIButton *checkLine=[UIButton buttonWithType:UIButtonTypeCustom];
        checkLine.tag=i+1;
        if (kScreenWidth==414) {
            checkLine.frame=CGRectMake(15+104*i+i*(kScreenWidth-30-104*3)/2, self.mapView.frame.origin.y+15, 104, 44);

        }else{
            checkLine.frame=CGRectMake(15+87*i+i*(kScreenWidth-30-87*3)/2, self.mapView.frame.origin.y+15, 87, 37);
        }
        checkLine.titleLabel.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT];

        [checkLine addTarget:self action:@selector(docheckLineType:) forControlEvents:UIControlEventTouchUpInside];
        [checkLine setBackgroundImage:[UIImage imageNamed:[arrays objectAtIndex:i]] forState:UIControlStateNormal];
        if (i==0) {
            [checkLine setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal];
        }
        else{
            [checkLine setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
        [checkLine setTitle:[titleArray objectAtIndex:i] forState:UIControlStateNormal];
        checkLine.titleEdgeInsets=UIEdgeInsetsMake(0, 30, 0, 0);
        [self.view addSubview:checkLine];
        }
//    [self searchTrafficTools:AMapSearchType_NaviDrive];

}
- (void)setnarBar
{
    self.navigationItem.title=@"路线";
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
}
-(void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  初始化地图
 */
- (void)creatMapView
{
    self.mapView=[[MAMapView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, CGRectGetHeight(self.view.frame)-44)];
//    NSLog(@"%f %f",kScreenWidth,kScreenHeight);
    
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    self.mapView.showsUserLocation=YES;
    self.mapView.showsCompass= NO;
    self.mapView.showsScale= NO;
    self.mapView.zoomLevel=13;
    
    //地图中心点   +0.001246     +0.006045
    CLLocationCoordinate2D coordinate2d;
    
    coordinate2d.latitude =self.lat;
    coordinate2d.longitude =self.lng;
    

    MACoordinateSpan span = MACoordinateSpanMake(0.025, 0.025);
    MACoordinateRegion region = MACoordinateRegionMake(coordinate2d, span);
    self.mapView.region = region;
    [self.mapView setCenterCoordinate:coordinate2d animated:YES];

    
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"请允许安好定位您的位置" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
    
    if ( IOS8_OR_LATER) {
        [self.locationManager requestAlwaysAuthorization];
    }
#endif
    self.locationManager.distanceFilter = 5.0;
    [self.locationManager startUpdatingLocation];

    //终点标注
    CLLocationCoordinate2D coordinate;
    
    if (self.isFromStore) {
        coordinate.latitude =self.p.location.latitude;
        coordinate.longitude =self.p.location.longitude;
    }else if(self.isFromHosp)
    {
        CGFloat lati=self.lattited;
        CGFloat lngd=self.lngtited;
        coordinate.latitude =lati;
        coordinate.longitude =lngd;
    }
    else
    {
        CGFloat lati=[[self.destinationDic valueForKey:@"lat"] floatValue];
        CGFloat lngd=[[self.destinationDic valueForKey:@"lng"] floatValue];
        coordinate.latitude =lati;
        coordinate.longitude =lngd;
    }
    
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc]init];
    annotation.coordinate=coordinate;
    annotation.title=@"终点";
    [self.mapView addAnnotation:annotation];
    [self.mapView selectAnnotation:annotation animated:YES];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *loc=[locations firstObject];
    self.lat = loc.coordinate.latitude;
    self.lng = loc.coordinate.longitude;
    CLLocationCoordinate2D coordinate;
    //+0.001246   +0.006045
    coordinate.latitude=loc.coordinate.latitude;
    coordinate.longitude=loc.coordinate.longitude;
    MACoordinateSpan span = MACoordinateSpanMake(0.05, 0.05);
    MACoordinateRegion region = MACoordinateRegionMake(coordinate, span);
    [self.mapView setRegion:region animated:YES];
    self.mapView.showsUserLocation=YES;
    [self searchReGeocode];
}
//逆地理编码描述
- (void)searchReGeocode
{
    self.search = [[AMapSearchAPI alloc] initWithSearchKey:@"c36674eca6a6cb5e40526f275ed4d241" Delegate:self];
    self.search.delegate = self;
    AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
    regeoRequest.searchType = AMapSearchType_ReGeocode;
    regeoRequest.location= [AMapGeoPoint locationWithLatitude:self.lat longitude:self.lng];
    
    regeoRequest.radius = 1000;
    regeoRequest.requireExtension = YES;
    [self.search AMapReGoecodeSearch: regeoRequest];
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    self.cityName=[[response.regeocode valueForKey:@"addressComponent"] valueForKey:@"province"];
    [self searchTrafficTools:AMapSearchType_NaviDrive];
}


//选择交通工具及其路线
- (void)docheckLineType:(UIButton *)sender
{
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"请允许安好定位您的位置" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return ;
    }
    [self showActionView];
    //+0.001246    +0.006045
    [self.mapView removeOverlay:redline];
    CLLocationCoordinate2D coordinate;
    coordinate.latitude=self.lat;
    coordinate.longitude=self.lng;
    MACoordinateSpan span = MACoordinateSpanMake(0.05, 0.05);
    MACoordinateRegion region = MACoordinateRegionMake(coordinate, span);
    [self.mapView setRegion:region animated:YES];
    switch (sender.tag) {
        case 1:
        {
            [self searchTrafficTools:AMapSearchType_NaviDrive];
            [sender setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_diringSelect@2x.png"] forState:UIControlStateNormal];
            [sender setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal];
            UIButton *btn2=(UIButton *)[self.view viewWithTag:2];
            [btn2 setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_bus@2x.png"] forState:UIControlStateNormal];
            [btn2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            
            
            UIButton *btn3=(UIButton *)[self.view viewWithTag:3];
            [btn3 setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_walk@2x.png"] forState:UIControlStateNormal];
            [btn3 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            
        }
            break;
        case 2:
        {
            [self searchTrafficTools:AMapSearchType_NaviBus];
            [sender setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_busSelect@2x.png"] forState:UIControlStateNormal];
            [sender setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal];
            
            UIButton *btn1=(UIButton *)[self.view viewWithTag:1];
            [btn1 setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_driving@2x.png"] forState:UIControlStateNormal];
            [btn1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            
            UIButton *btn3=(UIButton *)[self.view viewWithTag:3];
            [btn3 setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_walk@2x.png"] forState:UIControlStateNormal];
            [btn3 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
            break;
        case 3:
        {
            [self searchTrafficTools:AMapSearchType_NaviWalking];
            [sender setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_walkSelect@2x.png"] forState:UIControlStateNormal];
            [sender setTitleColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16] forState:UIControlStateNormal];
            
            UIButton *btn1=(UIButton *)[self.view viewWithTag:1];
            [btn1 setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_driving@2x.png"] forState:UIControlStateNormal];
            [btn1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            
            UIButton *btn2=(UIButton *)[self.view viewWithTag:2];
            [btn2 setBackgroundImage:[UIImage imageNamed:@"nearbyDrug_bus@2x.png"] forState:UIControlStateNormal];
            [btn2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
            break;
            
        default:
            break;
    }
}

/**
 *  初始化一下toolbar上 的控键，以及显示。
 */
- (void)initToolbarwithDetail
{
    self.toolView=[[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight-64-44-height, kScreenWidth, 44+height)];
    
    self.toolView.backgroundColor= [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.toolView];
    //上一步按钮，
    UIButton *leftButton=[UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame=CGRectMake(15,15, 10+height, 10+height);
    [leftButton setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    leftButton.imageEdgeInsets=UIEdgeInsetsMake(15, 15, 15, 15);
    
    //下一步按钮
    UIButton *rightButton=[UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.frame=CGRectMake(kScreenWidth-25-height, 15, 10+height, 10+height);
    [rightButton setBackgroundImage:[UIImage imageNamed:@"go.png"] forState:UIControlStateNormal];
    rightButton.imageEdgeInsets=UIEdgeInsetsMake(15, 15, 15, 15);
    [self.toolView addSubview:leftButton];
    [self.toolView addSubview:rightButton];
    
    //上一步手势
    UIImageView *backImageview=[[UIImageView alloc] initWithFrame:CGRectMake(5, 2, 40, 40)];
    [self.toolView addSubview:backImageview];
    backImageview.userInteractionEnabled=YES;
    UITapGestureRecognizer *backTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doleft:)];
    [backImageview addGestureRecognizer:backTap];
    
    UIImageView *goImageview=[[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth-50, 2, 40, 40)];
    [goImageview setContentMode:UIViewContentModeCenter];
    goImageview.userInteractionEnabled=YES;
    [self.toolView addSubview:goImageview];
    UITapGestureRecognizer *goTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doright:)];
    [goImageview addGestureRecognizer:goTap];
    //下一步手势
    //中间显示路线
    detailLabel=[[UILabel alloc]initWithFrame:CGRectMake(45,(self.toolView.height-20-height)/2, kScreenWidth-90,  20+height)];
    
    detailLabel.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT];

    detailLabel.lineBreakMode=NSLineBreakByWordWrapping;
    detailLabel.backgroundColor=[UIColor clearColor];
    detailLabel.textAlignment=NSTextAlignmentCenter;
    detailLabel.textColor=[UIColor whiteColor];
    detailLabel.numberOfLines=2;
    [self.toolView addSubview:detailLabel];
    
}
#pragma  mark  -------------划线
- (void)redLine:(NSInteger)index
{
    NSInteger count=[[zoomUpLats objectAtIndex:index] count];
    CLLocationCoordinate2D polylineCoords[count];
    for (int i=0; i<[[zoomUpLats objectAtIndex:index] count]; i++) {
        polylineCoords[i].latitude = [[[zoomUpLats objectAtIndex:index] objectAtIndex:i] doubleValue] ;
        polylineCoords[i].longitude=[[[zoomUpLngs objectAtIndex:index] objectAtIndex:i] doubleValue]  ;
        if (i==0) {
            CLLocationCoordinate2D coordinate;
            coordinate.latitude=polylineCoords[i].latitude;
            coordinate.longitude=polylineCoords[i].longitude;
            MACoordinateSpan span = MACoordinateSpanMake(0.008, 0.008);
            MACoordinateRegion region = MACoordinateRegionMake(coordinate, span);
            [self.mapView setRegion:region animated:YES];
        }
    }
    redline = [MAPolyline polylineWithCoordinates:polylineCoords count:count];
    [self.mapView addOverlay:redline];
}

#pragma mark  上一步----------------下一步
/**
 *  点击向左
 */
-(void)doright:(UITapGestureRecognizer *)btn
{
    if (detailcount==[self.detailStepArray count]) {
        //不能在往下一步
        return;
    }
    else{
        detailcount++;
        detailLabel.text=[NSString stringWithFormat:@"第%ld步,%@",detailcount,[self.detailStepArray objectAtIndex:detailcount-1]];
        CGSize size =CGSizeMake(kScreenWidth-90,0);
        //    获取当前文本的属性//
        detailLabel.lineBreakMode=NSLineBreakByWordWrapping;
//        detailLabel.font=[UIFont systemFontOfSize:13];
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:detailLabel.font,NSFontAttributeName,nil];
        CGSize  actualsize;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){
            actualsize =[detailLabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine  attributes:tdic context:nil].size;
            
        }
        if (actualsize.height<=20) {
            if (kScreenWidth==414) {
                detailLabel.frame=CGRectMake(45, 9+5, kScreenWidth-90, 21);

            }else{
                detailLabel.frame=CGRectMake(45, 9, kScreenWidth-90, 21);
 
            }
            detailLabel.textAlignment=NSTextAlignmentCenter;
        }
        else
        {
            detailLabel.textAlignment=NSTextAlignmentLeft;
            if (kScreenWidth==414) {
                detailLabel.frame=CGRectMake(49, (self.toolView.height-actualsize.height-height)/2+3, kScreenWidth-90, actualsize.height) ;
            }else{
                detailLabel.frame=CGRectMake(49, (self.toolView.height-actualsize.height-height)/2, kScreenWidth-90, actualsize.height) ;
            }
            
        }
        [self.mapView removeOverlay:redline];
        [self redLine:detailcount-1];
        
    }
}
/**
 *  点击向右
 */
-(void)doleft:(UITapGestureRecognizer *)btn
{
    if (detailcount==1) {
        return;
        //不能在往上一步了
    }
    else{
        detailcount--;
        detailLabel.text=[NSString stringWithFormat:@"第%ld步,%@",(long)detailcount,[self.detailStepArray objectAtIndex:detailcount-1]];
        CGSize size =CGSizeMake(kScreenWidth-90,0);
        //    获取当前文本的属性//
        detailLabel.lineBreakMode=NSLineBreakByWordWrapping;
        
//        detailLabel.font=[UIFont systemFontOfSize:14];
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:detailLabel.font,NSFontAttributeName,nil];
        CGSize  actualsize;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){
            actualsize =[detailLabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine  attributes:tdic context:nil].size;
        }
        if (actualsize.height<=20) {
            if (kScreenWidth==414) {
                detailLabel.frame=CGRectMake(45, 9+5, kScreenWidth-90, 21);
            }
            else{
                detailLabel.frame=CGRectMake(45, 9, kScreenWidth-90, 21);
            }
            detailLabel.textAlignment=NSTextAlignmentCenter;
        }
        else
        {
            detailLabel.textAlignment=NSTextAlignmentLeft;
            if (kScreenWidth==414) {
                detailLabel.frame=CGRectMake(49, (self.toolView.height-actualsize.height-height)/2+3, kScreenWidth-90, actualsize.height) ;
            }else{
                detailLabel.frame=CGRectMake(49, (self.toolView.height-actualsize.height-height)/2, kScreenWidth-90, actualsize.height) ;
            }        }
        [self.mapView removeOverlay:redline];
        [self redLine:detailcount-1];
    }
}
- (void)searchTrafficTools:(AMapSearchType )type
{
    [self showActionView];
    if (!self.search) {
        self.search = [[AMapSearchAPI alloc] initWithSearchKey:@"c36674eca6a6cb5e40526f275ed4d241" Delegate:self];

    }
//    self.search.delegate = self;
    AMapNavigationSearchRequest *naviRequest = [[AMapNavigationSearchRequest alloc] init];
    naviRequest.searchType = type;
    naviRequest.origin = [AMapGeoPoint locationWithLatitude:self.lat+0.001246 longitude:self.lng+0.006045];
    if (self.isFromStore) {
        naviRequest.destination=[AMapGeoPoint locationWithLatitude:self.p.location.latitude longitude:self.p.location.longitude];
    }else if (self.isFromHosp)
    {
        naviRequest.destination=[AMapGeoPoint locationWithLatitude:self.lattited longitude:self.lngtited];
    }
    else
    {
        CGFloat lati=[[self.destinationDic valueForKey:@"lat"] floatValue];
        CGFloat lngd=[[self.destinationDic valueForKey:@"lng"] floatValue];
        naviRequest.destination=[AMapGeoPoint locationWithLatitude:lati longitude:lngd];
    }

    if (type==AMapSearchType_NaviBus) {
        naviRequest.city=self.cityName;
    }
    [self.search AMapNavigationSearch: naviRequest];
}
#pragma  mark 大头针的代理
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[MAAnnotationView class]]) {
        MAAnnotationView* pinView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];
        if (pinView == nil) {
            pinView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID"];
        }
        //pinView.pinColor = MKPinAnnotationColorPurple;
        pinView.userInteractionEnabled = YES;
        //显示,no的话重写annotation不会自己显示
        pinView.canShowCallout = YES;
        //大头针从上方掉落下来效果
        return pinView;
    }
    return nil;
}
#pragma  mark 返回的路线代理路线代理
- (void)reloadBusLine:(NSDictionary *)dict
{
    //清除之前数据
    [zoomUpLats removeAllObjects];
    [zoomUpLngs removeAllObjects];
    [self.detailStepArray removeAllObjects];
    detailcount=1;
    [self.illHospitalLatArr removeAllObjects];
    [self.illHospitalLonArr removeAllObjects];
    [self.mapView removeOverlay: self.polyline];
    detailLabel.text=@"";
    
    for (int i=0; i<[[dict valueForKey:@"segments"] count]; i++) {
        //步行路线及步行信息
        NSArray *walkArray=[[[[dict valueForKey:@"segments"] objectAtIndex:i]valueForKey:@"walking"] valueForKey:@"steps"];
        NSMutableArray *walkLat=[[NSMutableArray alloc]init];
        NSMutableArray *walkLng=[[NSMutableArray alloc]init];
        
        for (int j=0; j<walkArray.count; j++) {
            NSArray *coordidateArray=[[[walkArray objectAtIndex:j] valueForKey:@"polyline"] componentsSeparatedByString:@";"];
            for (int m=0; m<coordidateArray.count; m++) {
                NSRange seachRange=[[coordidateArray objectAtIndex:m] rangeOfString:@","];
                [self.illHospitalLatArr addObject:[[coordidateArray objectAtIndex:m] substringFromIndex:seachRange.location+1]];
                [self.illHospitalLonArr addObject:[[coordidateArray objectAtIndex:m] substringToIndex:seachRange.location]];
                [walkLat addObject:[[coordidateArray objectAtIndex:m] substringFromIndex:seachRange.location+1]];
                [walkLng addObject:[[coordidateArray objectAtIndex:m] substringToIndex:seachRange.location]];
            }
        }
        
        [zoomUpLats addObject:walkLat];
        [zoomUpLngs addObject:walkLng];
        
        NSString *walkStr=[NSString stringWithFormat:@"步行%@米,%@站",[[[[dict valueForKey:@"segments"] objectAtIndex:i]valueForKey:@"walking"] valueForKey:@"distance"],[[walkArray objectAtIndex:[walkArray count]-1]valueForKey:@"assistantAction"]];
        [self.detailStepArray addObject:walkStr];
        //公交路线及信息
        if ([[[dict valueForKey:@"segments"] objectAtIndex:i]valueForKey:@"busline"])
        {
            NSMutableArray *busLats=[[NSMutableArray alloc]init];
            NSMutableArray *busLngs=[[NSMutableArray alloc]init];
            NSDictionary *busLine=[[[dict valueForKey:@"segments"] objectAtIndex:i]valueForKey:@"busline"];
            NSArray *busCoordotateArray=[[busLine valueForKey:@"polyline"] componentsSeparatedByString:@";"];
            for (int n=0; n<busCoordotateArray.count; n++) {
                NSRange seachRange=[[busCoordotateArray objectAtIndex:n] rangeOfString:@","];
                [self.illHospitalLatArr addObject:[[busCoordotateArray objectAtIndex:n] substringFromIndex:seachRange.location+1]];
                [self.illHospitalLonArr addObject:[[busCoordotateArray objectAtIndex:n] substringToIndex:seachRange.location]];
                [busLats addObject:[[busCoordotateArray objectAtIndex:n] substringFromIndex:seachRange.location+1]];
                [busLngs addObject:[[busCoordotateArray objectAtIndex:n] substringToIndex:seachRange.location]];
            }
            [zoomUpLats addObject:busLats];
            [zoomUpLngs addObject:busLngs];
            
            NSString *busStr=[NSString stringWithFormat:@"乘坐%@,经过%ld站,在%@下车",[busLine valueForKey:@"name"],[[busLine valueForKey:@"busStops"] count]+1,[[busLine valueForKey:@"arrivalStop"] valueForKey:@"name"]];
            [self.detailStepArray addObject:busStr];
        }
    }
    [self LineOverlay];
}
#pragma mark  搜索附近药店路线完成后执行的代理方法。经纬度坐标,根据获得的经纬度画线。
- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
    [self hiddenActionView ];
}
- (void)onNavigationSearchDone:(AMapNavigationSearchRequest *)request response:(AMapNavigationSearchResponse *)response
{
    [self hiddenActionView ];

    if (response == nil)
    {
        return;
    }
    [self hiddenActionView ];
    if (request.searchType==AMapSearchType_NaviBus) {
        BusListViewController *busList=[[BusListViewController alloc]init];
        busList.delegate=self;
        busList.allBusLists=[[response route] valueForKey:@"transits"];
        busList.taxiCost=[NSString stringWithFormat:@"%ld",[[response.route valueForKey:@"taxiCost"] integerValue]];
        BaseNavigation *nav=[[BaseNavigation alloc]initWithRootViewController:busList];

        [self presentViewController:nav animated:YES completion:nil];
        
    }else
    {
        
        //清除之前数据
        [self.detailStepArray removeAllObjects];
        detailcount=1;
        [self.illHospitalLatArr removeAllObjects];
        [self.illHospitalLonArr removeAllObjects];
        [zoomUpLats removeAllObjects];
        [zoomUpLngs removeAllObjects];
        
        [self.mapView removeOverlay: self.polyline];
        detailLabel.text=@"";
        
        for (int j=0; j<[[[response.route.paths objectAtIndex:0] valueForKey:@"steps"] count]; j++) {
            NSArray *coordidateArray=[[[[[response.route.paths objectAtIndex:0] valueForKey:@"steps"] objectAtIndex:j] valueForKey:@"polyline"] componentsSeparatedByString:@";"];
            
            NSMutableArray *temLat=[[NSMutableArray alloc]init];
            NSMutableArray *temLng=[[NSMutableArray alloc]init];
            
            [self.detailStepArray addObject:[[[[response.route.paths objectAtIndex:0] valueForKey:@"steps"] objectAtIndex:j] valueForKey:@"instruction"]];
            
            for (int i=0; i< [coordidateArray count]; i++) {
                
                NSRange seachRange=[[coordidateArray objectAtIndex:i] rangeOfString:@","];
                
                [self.illHospitalLatArr addObject:[[coordidateArray objectAtIndex:i] substringFromIndex:seachRange.location+1]];
                [self.illHospitalLonArr addObject:[[coordidateArray objectAtIndex:i] substringToIndex:seachRange.location]];
                //临时存储经纬度
                [temLat addObject:[[coordidateArray objectAtIndex:i] substringFromIndex:seachRange.location+1]];
                [temLng addObject:[[coordidateArray objectAtIndex:i] substringToIndex:seachRange.location]];
            }
            [zoomUpLats addObject:temLat];
            [zoomUpLngs addObject:temLng];
        }
        [self LineOverlay];
    }
}

- (void)LineOverlay
{
    NSInteger count=[self.illHospitalLatArr count];
    CLLocationCoordinate2D polylineCoords[count];
    for (int i=0; i<[self.illHospitalLatArr count]; i++) {
        polylineCoords[i].latitude = [[self.illHospitalLatArr objectAtIndex:i] doubleValue] ;
        polylineCoords[i].longitude=[[self.illHospitalLonArr objectAtIndex:i] doubleValue]  ;
    }
    self.polyline = [MAPolyline polylineWithCoordinates:polylineCoords count:count];
    [self.mapView addOverlay:self.polyline];
    detailLabel.text=[NSString stringWithFormat:@"第%ld步,%@",detailcount,[self.detailStepArray objectAtIndex:detailcount-1]];
    
    CGSize size =CGSizeMake(kScreenWidth-90,0);
    //    获取当前文本的属性//
    detailLabel.lineBreakMode=NSLineBreakByWordWrapping;
    
//    detailLabel.font=[UIFont systemFontOfSize:14];
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:detailLabel.font,NSFontAttributeName,nil];
    CGSize  actualsize;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){
        actualsize =[detailLabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine  attributes:tdic context:nil].size;
    }
    if (actualsize.height<=20) {
        if (kScreenWidth==414) {
            detailLabel.frame=CGRectMake(45, 9+5, kScreenWidth-90, 21);
            
        }else{
            detailLabel.frame=CGRectMake(45, 9, kScreenWidth-90, 21);
            
        }
        detailLabel.textAlignment=NSTextAlignmentCenter;
    }
    else
    {
        detailLabel.textAlignment=NSTextAlignmentLeft;
        if (kScreenWidth==414) {
            detailLabel.frame=CGRectMake(49, (self.toolView.height-actualsize.height-height)/2+3, kScreenWidth-90, actualsize.height) ;
        }else{
            detailLabel.frame=CGRectMake(49, (self.toolView.height-actualsize.height-height)/2, kScreenWidth-90, actualsize.height) ;
        }
    }
    
}
//将折线添加到地图上，设置折线到颜色和粗细。
- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        if ([overlay isEqual:self.polyline]) {
            MAPolylineView *lineview=[[MAPolylineView alloc] initWithOverlay:overlay] ;
            lineview.strokeColor=[[UIColor colorWithRed:79.0/255 green:193.0/255 blue:233.0/255 alpha:1] colorWithAlphaComponent:1];
            lineview.lineWidth=4.0;
            return lineview;
        }else
        {
            MAPolylineView *lineview=[[MAPolylineView alloc] initWithOverlay:overlay] ;
            lineview.strokeColor=[[UIColor colorWithRed:255.0/255 green:157.0/255 blue:157.0/255 alpha:1] colorWithAlphaComponent:1];
            lineview.lineWidth=4.0;
            return lineview;
        }
    }
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillDisappear:(BOOL)animated
{
//    [self.mapView removeOverlay: self.polyline];
    self.mapView.delegate=nil;
    self.locationManager.delegate=nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
